package com.yx.yinshanjinniu.activitys;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.yx.yinshanjinniu.R;
import com.yx.yinshanjinniu.base.BaseActivity;
import com.yx.yinshanjinniu.bean.AddressBean;
import com.yx.yinshanjinniu.bean.CreateShopProductBean;
import com.yx.yinshanjinniu.bean.GoodsTicketInfoBean;
import com.yx.yinshanjinniu.bean.OrderInfoBean;
import com.yx.yinshanjinniu.bean.UserInfoBean;
import com.yx.yinshanjinniu.constants.Constant;
import com.yx.yinshanjinniu.net.ActionCallbackListener;
import com.yx.yinshanjinniu.utils.DataUtils;
import com.yx.yinshanjinniu.utils.GlideUtils;
import com.yx.yinshanjinniu.utils.GoodsUtils;
import com.yx.yinshanjinniu.utils.RouteUtil;
import com.yx.yinshanjinniu.utils.ToastUtil;
import com.yx.yinshanjinniu.view.MoneyTextView;
import com.zc.mychart.model.GoodsAllBean;
import com.zc.mychart.model.GoodsItemBean;
import com.zc.mychart.utils.ArithUtil;
import com.zc.mychart.utils.FormatUtil;

import java.util.List;

public class AddGoodsOrderActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout rl_address;
    private LinearLayout ll_address_info;
    private TextView tv_add_address;
    private TextView tv_user_info;
    private TextView tv_user_address;

    private MoneyTextView mtv_goods_money;
    private MoneyTextView mtv_ticket_money;
    private MoneyTextView mtv_material;
    private MoneyTextView mtv_material_support;
    private MoneyTextView mtv_premium;
    private MoneyTextView mtv_loss;
    private MoneyTextView mtv_technology;
    private MoneyTextView mtv_taxes;
    private MoneyTextView mtv_total_money;

    private ImageView iv_goods;
    private ImageView iv_sub;
    private ImageView iv_add;
    private TextView tv_number;
    private TextView tv_goods_name;
    private TextView tv_right;
    private Button btn_submit;

    private int mNumber = 1;
    private int mMaxNumber = 0;
    private double mTicketMoney = 0;
    private double mTotalMoney;

    private OrderInfoBean mOrderInfoBean;
    private GoodsItemBean mProInfoItemBean;
    private AddressBean mAddressBean;
    private GoodsAllBean mGroupBean;
    private String mTickId = "";//优惠券id
    private String mGoodsid = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mOrderInfoBean = (OrderInfoBean) getIntent().getSerializableExtra(RouteUtil.BUNDLE_ORDER_MODEL);
        initProGroup();
        initData();
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_add_goods_order;
    }

    @Override
    protected void findViews() {
        rl_address = findViewById(R.id.rl_address);
        ll_address_info = findViewById(R.id.ll_address_info);
        tv_add_address = findViewById(R.id.tv_add_address);
        tv_user_info = findViewById(R.id.tv_user_info);
        tv_user_address = findViewById(R.id.tv_user_address);

        mtv_goods_money = findViewById(R.id.mtv_goods_money);
        mtv_ticket_money = findViewById(R.id.mtv_ticket_money);
        mtv_material = findViewById(R.id.mtv_material);
        mtv_material_support = findViewById(R.id.mtv_material_support);
        mtv_premium = findViewById(R.id.mtv_premium);
        mtv_loss = findViewById(R.id.mtv_loss);
        mtv_technology = findViewById(R.id.mtv_technology);
        mtv_taxes = findViewById(R.id.mtv_taxes);
        mtv_total_money = findViewById(R.id.mtv_total_money);

        iv_goods = findViewById(R.id.iv_goods);
        iv_sub = findViewById(R.id.iv_sub);
        iv_add = findViewById(R.id.iv_add);
        tv_number = findViewById(R.id.tv_number);
        tv_goods_name = findViewById(R.id.tv_goods_name);
        tv_right = findViewById(R.id.tv_right);

        btn_submit = findViewById(R.id.btn_submit);

        setNumber();
    }

    /**
     * 设置监听
     */
    @Override
    protected void setListeners() {
        iv_add.setOnClickListener(this);
        iv_sub.setOnClickListener(this);
        rl_address.setOnClickListener(this);
        btn_submit.setOnClickListener(this);
        tv_right.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_address:
                RouteUtil.toAddressListActivity(this, RouteUtil.REQUEST_ADDRESS_LIST);
                break;
            case R.id.iv_add:
                if (mNumber < mMaxNumber) {
                    mNumber++;
                }
                setNumber();
                break;
            case R.id.iv_sub:
                if (mNumber == 1) {
                    mNumber = 1;
                } else {
                    mNumber--;
                }
                setNumber();
                break;
            case R.id.btn_submit:
                buyGoods();
                break;
            case R.id.tv_right:
                RouteUtil.toWebViewActivity(this, Constant.H5_DELIVERY_RULE);
                break;
        }
    }

    private void initProGroup() {
        if (null != mOrderInfoBean) {
            mGroupBean = myApplication.getAllGoodMap().get(mOrderInfoBean.pro_code);
        }
    }

    private void buyGoods(){
        CreateShopProductBean bean = new CreateShopProductBean();
        if (mAddressBean == null || TextUtils.isEmpty(mAddressBean.id)) {
            ToastUtil.showToast(mContext, "请选择零售订单地址");
            return;
        }
        UserInfoBean userInfo = DataUtils.getUserInfo(mContext);
        if (userInfo == null) return;
        if (mTotalMoney > userInfo.availablebalance){
            ToastUtil.showToast(mContext, "余额不足");
            return;
        }
        bean.address_id = mAddressBean.id;
        bean.amount = mNumber;
        bean.goods_id = mGoodsid;
        bean.couponId = mTickId;
        loading();
        mAppAction.createProduct(bean, new ActionCallbackListener<Void>() {
            @Override
            public void onSuccess(Void data) {
                cancelLoading();
                ToastUtil.showToast(mContext, "订单下单成功,进入\"我的->零售订单\"查看");
                RouteUtil.toMainActivity(AddGoodsOrderActivity.this, MainActivity.TAB_HOME);
            }

            @Override
            public void onFailure(String errorCode, String message) {
                cancelLoading();
                ToastUtil.showToast(mContext, message);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getAddressList();
    }

    private void initData() {
        getTicket();
        List<GoodsAllBean> allList = myApplication.getAllList();
        if (allList.isEmpty()){
            ToastUtil.showToast(mContext, "提货商品数据有误，请稍后再试");
            return;
        }
        for (int i = 0; i < allList.size(); i++) {
            for (GoodsItemBean goodsItemBean : allList.get(i).goods_list) {
                if (mOrderInfoBean.goods_id.equals(goodsItemBean.goods_id)){
                    mProInfoItemBean = goodsItemBean;
                    showProGroupBean();
                }
            }

        }
    }

    private void showProGroupBean() {
        if (null != mProInfoItemBean) {
            GlideUtils.showImageOptions(mContext, mProInfoItemBean.product_img, iv_goods);
            mtv_goods_money.setText(mProInfoItemBean.product_price + "");
            tv_goods_name.setText(mProInfoItemBean.pro_name);
            mMaxNumber = mOrderInfoBean.amount;
            setNumber();
        }
    }

    private void setNumber() {
        if (null != mProInfoItemBean) {
            mTotalMoney = GoodsUtils.setGoodsMoneyCalculate(mGroupBean.latest_price, mNumber, mProInfoItemBean,
                    mtv_material, mtv_material_support, mtv_premium, mtv_loss, mtv_technology, mtv_taxes);
//            mTotalMoney = ArithUtil.mul(mNumber, Double.parseDouble(mProInfoItemBean.getProduct_price()));
            mTotalMoney = ArithUtil.sub(mTotalMoney, mTicketMoney);
            if (mTotalMoney < 0) {
                mTotalMoney = 0;
            }
            mtv_total_money.setText(FormatUtil.formatDouble2(mTotalMoney));
        }
        tv_number.setText(String.valueOf(mNumber));
    }

    private void setAddress() {
        if (null != mAddressBean) {
            tv_add_address.setVisibility(View.GONE);
            ll_address_info.setVisibility(View.VISIBLE);

            String user_info = mAddressBean.name + " " + mAddressBean.mobile;
            String address = mAddressBean.region + " " + mAddressBean.address;
            tv_user_info.setText(user_info);
            tv_user_address.setText(address);
        } else {
            tv_add_address.setVisibility(View.VISIBLE);
            ll_address_info.setVisibility(View.GONE);
        }
    }

    private void getAddressList() {
        mAppAction.getAddressList(new ActionCallbackListener<List<AddressBean>>() {
            @Override
            public void onSuccess(List<AddressBean> data) {
                cancelLoading();
                for (AddressBean bean : data) {
                    if (null == mAddressBean && bean.is_default == 1) {
                        mAddressBean = bean;
                    } else if (null != mAddressBean) {
                        if (mAddressBean.id.equals(bean.id)) {
                            mAddressBean = bean;
                        }
                    }
                }
                boolean contains = data.contains(mAddressBean);
                if (!contains) {
                    mAddressBean = null;
                }
                setAddress();
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showToast(mContext, message);
            }
        });
    }

    /**
     * 获取零售券
     */
    private void getTicket() {
        mAppAction.getRetailTicket(mOrderInfoBean.goods_id, 3, new ActionCallbackListener<GoodsTicketInfoBean>() {
            @Override
            public void onSuccess(GoodsTicketInfoBean data) {
                mTickId = data.couponId;
                mTicketMoney = data.faceValue;
                mtv_ticket_money.setText("-" + mTicketMoney);
                setNumber();
            }

            @Override
            public void onFailure(String errorCode, String message) {
//                ToastUtil.showToast(mContext, message);
            }
        });
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && data.getExtras() != null) {
            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == RouteUtil.REQUEST_ADDRESS_LIST) {
                    mAddressBean = (AddressBean) data.getExtras().get(RouteUtil.BUNDLE_ADDRESS);
                    setAddress();
                }
            }
        }
    }

}
